package com.edou.member.controller.weixin;

import java.io.File;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.constant.SessionConstant;
import com.edou.base.controller.BaseController;
import com.edou.base.form.ImageCropForm;
import com.edou.base.util.EncryptUtil;
import com.edou.base.util.ImageUtil;
import com.edou.member.entity.MemberUser;
import com.edou.member.form.MemberUserForm;
import com.edou.member.service.IMemberUserService;

/**
 * 会员帐号模块
 * @creator     admin
 * @create-time 2016/3/12 16:10:22
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("memberUserAccountWeixinController")
@Scope("prototype")
@RequestMapping("/weixin/member/account")
public class MemberUserAccountWeixinController extends BaseController {

	@Resource(name = "memberUserServiceImpl")
	private IMemberUserService memberUserService;
	
	@Autowired(required = false)
	private ServletContext servletContext;
	
	/**
	 * 跳转到会员修改密码页
	 * @return 
	 */
	@RequestMapping(value = "/password.htm", method = RequestMethod.GET)
	public String password(){
		return "/member/account/password";
	}
	
	/**
	 * 验证原密码是否正确
	 * @return 
	 */
	@RequestMapping(value = "/check_password.htm", method = RequestMethod.POST)
	public ModelAndView checkPassword(MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		
		String oldPassword = model.getOldPassword();
		if(StringUtils.isBlank(oldPassword)){
			return ajaxJSON(Status.success,"false");
		}
		
		MemberUser memberUser = (MemberUser)session.getAttribute(SessionConstant.CURRENT_MEMBER);
		MemberUser memberUserDB = memberUserService.getMemberUserById(memberUser.getId());
		
		String oldPasswordEncry = EncryptUtil.encryptionPw(oldPassword);
		
		if(StringUtils.isNotBlank(oldPasswordEncry) && oldPasswordEncry.equals(memberUserDB.getPassword())){
			return ajaxJSON(Status.success,"true");
		} else {
			return ajaxJSON(Status.success,"false");
		}
	}
	
	/**
	 * 密码修改
	 * @return 
	 */
	@RequestMapping(value = "/do_update_pwd.htm", method = RequestMethod.POST)
	public ModelAndView doUpdatePwd(MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		try{
			String password = model.getPassword();
			MemberUser memberUser = (MemberUser)session.getAttribute(SessionConstant.CURRENT_MEMBER);
			memberUser.setPassword(password);
			memberUserService.updatePwd(memberUser);
			
			return ajaxJSON(Status.success,"修改成功");
		}catch(Exception e){
			e.printStackTrace();
			return ajaxJSON(Status.error,"修改失败");
		}
	}
	
	/**
	 * 跳转到图片裁剪的页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/image_crop.htm", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView imageCrop(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		ModelAndView view = new ModelAndView();
		JSONParser p = new JSONParser();
		view.setViewName("/member/account/image_crop");
		String postData = (String)request.getParameter("postData");
		view.addObject("postData",p.parse(postData));
		return view;
	}
	
	/**
	 * 保存头像
	 * @param model
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/save_face_photo.htm",method = RequestMethod.POST)
	public ModelAndView add_picture(@ModelAttribute ImageCropForm cropModel, HttpServletRequest request,HttpSession session){
		try{
			MemberUser member = (MemberUser)session.getAttribute(SessionConstant.CURRENT_MEMBER);
			String fileRoot = (String)servletContext.getAttribute("fileRoot");
			String realPath = getRealPath(fileRoot, request);
			// 得到文件路径
			String src = cropModel.getPhoto();
			// 得到文件名
			String fileName = src.substring(0, src.indexOf("."));
			// 得到文件的后缀名
			String fileExt = src.substring(src.indexOf("."));
			// 目标地址
			String cutDesc = fileName + "-cut" + fileExt;
			String bigDesc = fileName + "-B" + fileExt;
			String middleDesc = fileName + "-M" + fileExt;
			String smallDesc = fileName + "-S" + fileExt;
			int[] sourceWAndH = ImageUtil.getImageWAndH(realPath + src);
			// 等比缩放后结果
			double x = sourceWAndH[0] / (double)cropModel.getBroundX() * cropModel.getX();
			double y = sourceWAndH[1] / (double)cropModel.getBroundY() * cropModel.getY();
			double w = sourceWAndH[0] / (double)cropModel.getBroundX() * cropModel.getW();
			double h = sourceWAndH[1] / (double)cropModel.getBroundY() * cropModel.getH();
			// 裁剪图片
			ImageUtil.cutImage(realPath + src,realPath + cutDesc, (int)x , (int)y,(int)w, (int)h,fileExt.substring(1).toLowerCase());
			// 缩放得到大图片
			ImageUtil.zoomImage(realPath + cutDesc, realPath + bigDesc, cropModel.getWidth(), cropModel.getHeight());
			// 缩放中等图片
			ImageUtil.zoomImage(realPath + bigDesc, realPath + middleDesc, cropModel.getWidth()/2, cropModel.getHeight()/2);
			// 缩放小图片
			ImageUtil.zoomImage(realPath + bigDesc, realPath + smallDesc, cropModel.getWidth()/4, cropModel.getHeight()/4);
			// 删除原图与裁剪后的图片
			FileUtils.deleteQuietly(new File(realPath + src));
			FileUtils.deleteQuietly(new File(realPath + cutDesc));
			member.setFacePath(middleDesc);
			memberUserService.updateFacePath(member);
			
			// 重新更新Session中的会员信息
			MemberUser currentMember = (MemberUser)session.getAttribute(SessionConstant.CURRENT_MEMBER);
			currentMember.setFacePath(middleDesc);
			session.setAttribute(SessionConstant.CURRENT_MEMBER, currentMember);
			
			return ajaxJSON(Status.success,middleDesc);
		}catch(Exception e){
			String msg = "裁剪图片发生异常:" + e.getMessage();
			logger.error(msg, e);
			return ajaxJSON(Status.error);
		}
	}
	
}